package com.webdev.base.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.webdev.base.mapper.GoodsMapper;
import com.webdev.base.pojo.Goods;
import com.webdev.base.service.IGoodsService;
import com.webdev.base.util.Constants;
import com.webdev.base.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author huangningshuang
 * @since 2021-12-13
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<GoodsVo> findGoodsVoList() {
        return goodsMapper.findGoodsVoList();
    }

    @Override
    public GoodsVo findGoodsVoByGoodId(Integer goodsId) {
        return goodsMapper.findGoodsVoByGoodId(goodsId);
    }

    @Override
    public Integer deleteGoodsById(Integer goodsId) {
        redisTemplate.delete(Constants.REDIS_GOODSKEY + goodsId);
        redisTemplate.delete(Constants.REDIS_GOODSSTARTKEY + goodsId);
        redisTemplate.delete(Constants.REDIS_GOODSENDKEY + goodsId);
        redisTemplate.delete(Constants.REDIS_EMPTYGOODSKEY + goodsId);
        return goodsMapper.deleteGoodsById(goodsId);
    }

    private void updateRedis(GoodsVo goodsVo) {
        redisTemplate.opsForValue().set(Constants.REDIS_GOODSKEY + goodsVo.getGoodsId(), goodsVo.getGoodsCount());
        redisTemplate.opsForValue().set(Constants.REDIS_GOODSSTARTKEY + goodsVo.getGoodsId(), goodsVo.getStartDate());
        redisTemplate.opsForValue().set(Constants.REDIS_GOODSENDKEY + goodsVo.getGoodsId(), goodsVo.getEndDate());
        if (goodsVo.getGoodsCount() <= 0) {
            redisTemplate.opsForValue().set(Constants.REDIS_EMPTYGOODSKEY + goodsVo.getGoodsId(), true);
        }
    }

    @Override
    public void insertGoods(GoodsVo goodsVo) {
        goodsMapper.insertGoods(goodsVo);
        System.out.println("goodsVo.getGoodsId() = " + goodsVo.getGoodsId());
        updateRedis(goodsVo);
    }

    @Override
    public Integer updateById(Integer goodsId, GoodsVo goodsVo) {
        goodsVo.setGoodsId(goodsId);
        Integer row = goodsMapper.updateById(goodsVo);
        if (row == 1) updateRedis(goodsVo);
        return row;
    }
}
